<template v-else>
  <div v-if="editable" class="week-enabler">
    <checkbox-options
      v-model="values"
      :options="options"
      @change="onWeekChange"
    />
  </div>
  <div v-else class="week-enabler">
    <el-tag
      v-for="(b, week) in weekEanbleBits"
      :key="week"
      :type="+b ? 'primary' : 'info'"
      :hit="!!+b"
      :class="['week', +b && 'active']"
      >
        {{trans[week]}}
      </el-tag>
    </div>
  </template>

<script>
import CheckboxOptions from '@/components/CheckboxOptions';

export default {
  components: {
    CheckboxOptions
  },
  model: {
    event: 'change'
  },
  props: {
    // 默认值 格式如1010101
    value: [String, Array],
    editable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    this.trans = ['日', '一', '二', '三', '四', '五', '六'];
    this.options = this.trans.map((weekText, index) => ({text: '周' + weekText, value: index}));

    return {
      values: this.enableBitsToValues(this.value)
    };
  },
  computed: {
    weekEanbleBits() {
      return this.value.split('').map(Number);
    }
  },
  watch: {
    value(newValue, oldValue) {
      let newValues = this.enableBitsToValues(newValue);
      let oldValues = this.enableBitsToValues(oldValue);
      let isEquals = true;
      if (newValues.length != oldValues.length) {
        isEquals = false;
      } else {
        for (let i = 0, l = newValues.length; i < l; i++) {
          if (newValues[i] != oldValues[i]) {
            isEquals = false;
            break;
          }
        }
      }
      if (!isEquals) {
        this.values = newValues;
      }
    }
  },
  methods: {
    onWeekChange(week) {
      this.$emit('change', this.valuesToEnableBits(this.values));
    },
    enableBitsToValues(enableBits) {
      enableBits = enableBits
        ? typeof enableBits == 'string' ? enableBits.split('').map(Number) : enableBits
        : new Array(7).fill(0);
      let values = [];
      enableBits.forEach((enable, index) => {
        if (enable)
          values.push(index);
      });
      return values;
    },
    valuesToEnableBits(values) {
      let enableBits = new Array(7).fill(0);
      values.forEach((index) => {
        enableBits[index] = 1;
      });
      return enableBits;
    }
  }
}
</script>

<style scoped>
.week-enabler {
  display: inline-block;
  user-select: none;
}

.week-enabler .el-tag.week {
  margin-right: 3px;
}

.el-tag.week:not(.active) {
  color: #dddddd;
}
</style>